﻿using System;
using System.Drawing.Imaging;
using System.Drawing;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Avalonia.Markup.Xaml;
using Avalonia;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Avalonia.Controls.ApplicationLifetimes;

namespace DX
{
    class AppStart
    {

    }
    class AppStart<TApp> : AppStart where TApp : Avalonia.Application
    {

        public AppStart(IServiceProvider serviceProvider, INotifyCenter notificationCenter, ILogger<AppStart<TApp>> logger, IHostApplicationLifetime lifetime)
        {
            this.serviceProvider = serviceProvider;
            this.notificationCenter = notificationCenter;
            this.logger = logger;
            this.lifetime = lifetime;
            lifetime.ApplicationStarted.Register(OnApplicationStarted);
            lifetime.ApplicationStopping.Register(OnApplicationStopping);

        }

        private readonly IServiceProvider serviceProvider;
        private readonly INotifyCenter notificationCenter;
        private readonly ILogger logger;
        private readonly IHostApplicationLifetime lifetime;

        private void OnApplicationStopping()
        {

            notificationCenter.Close();



        }

        private void OnApplicationStarted()
        {
            logger.LogInformation("Application Started");

            RunApp();
        }
        AppBuilder BuildAvaloniaApp()
        {
            return AppBuilder.Configure<TApp>(_appFactory)
                  .UsePlatformDetect()
                  .WithInterFont()
                  .LogToTrace();
        }
        Func<TApp> _appFactory;
        private void RunApp()
        {
            _appFactory = () =>
            {
                return (TApp)serviceProvider.GetService<Application>();
            };
            var applifetime = serviceProvider.GetService<IClassicDesktopStyleApplicationLifetime>() as ClassicDesktopStyleApplicationLifetime;
            try
            {




                var appbuiler = BuildAvaloniaApp();

                var method = typeof(ClassicDesktopStyleApplicationLifetime).GetMethod("SubscribeGlobalEvents", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
                method.Invoke(applifetime, null);
                applifetime.ShutdownMode = Avalonia.Controls.ShutdownMode.OnMainWindowClose;
                appbuiler.SetupWithLifetime(applifetime);
                notificationCenter.Create();
                notificationCenter.Add("退出", () =>
                {
                    applifetime.Shutdown();
                });
                applifetime.Start();

                logger.LogInformation($"UI closeing");


            }
            catch (Exception e)
            {
                logger.LogError(e,"RunApp error {MainWindow}", applifetime.MainWindow);
                throw;
            }
            finally
            {
                OnApplicationStopping();
                applifetime.Shutdown();
                lifetime.StopApplication();
            }
        }

        public Task StartAsync(CancellationToken cancellationToken)
        {





            return Task.CompletedTask;
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {

            return Task.CompletedTask;
        }
    }
}
